package com.cssw.fyzb.tps.client;

import com.cssw.fyzb.tps.model.vo.CredentialsVo;
import com.tencentcloudapi.common.Credential;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import com.tencentcloudapi.common.profile.ClientProfile;
import com.tencentcloudapi.common.profile.HttpProfile;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenRequest;
import com.tencentcloudapi.sts.v20180813.models.GetFederationTokenResponse;
import lombok.Getter;
import lombok.Setter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

/**
 * @author Feng Chen
 */
@Component
@Setter
@Getter
public class StsClient {

    @Value("${sts.secretId}")
    private String secretId;

    @Value("${sts.secretKey}")
    private String secretKey;

    @Value("${sts.region}")
    private String region;

    @Value("${sts.endpoint}")
    private String endpoint;

    private static final Logger logger = LoggerFactory.getLogger(StsClient.class);

    public CredentialsVo getFederationToken(String policy) {

        CredentialsVo credentialsVo = null;
        Credential cred = new Credential(secretId, secretKey);

        HttpProfile httpProfile = new HttpProfile();
        httpProfile.setEndpoint(endpoint);

        ClientProfile clientProfile = new ClientProfile();
        clientProfile.setHttpProfile(httpProfile);

        com.tencentcloudapi.sts.v20180813.StsClient client = new com.tencentcloudapi.sts.v20180813.StsClient(cred, region, clientProfile);

        GetFederationTokenRequest req = new GetFederationTokenRequest();
        req.setName("GetFederationToken");
        req.setPolicy(policy);

        try {
            GetFederationTokenResponse resp = client.GetFederationToken(req);

            credentialsVo = new CredentialsVo();

            credentialsVo.setExpireTime(resp.getExpiredTime());
            credentialsVo.setRequestId(resp.getRequestId());
            credentialsVo.setSessionToken(resp.getCredentials().getToken());
            credentialsVo.setTmpSecretId(resp.getCredentials().getTmpSecretId());
            credentialsVo.setTmpSecretKey(resp.getCredentials().getTmpSecretKey());

        } catch (TencentCloudSDKException e) {
            logger.error("", e);
        }

        return credentialsVo;
    }


}
